package com.zhuhai.util;

import com.zhuhai.entity.Passenger;
import com.zhuhai.entity.Pnr;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * Specification工具类
 *
 *  @author zhuhai
 *  @version 1.0.0.0
 */
public class SpecificationUtil {

    /**
     * 获取旅客Specification
     * @param issueOfficeCode
     * @param type
     * @return
     */
    public static Specification<Passenger> getPassengerSpecification(final String issueOfficeCode,
                                                                     final String type) {
        final Specification<Passenger> specification = (root, query, cb) -> {
                final List<Predicate> lstPredicates = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(issueOfficeCode)) {
                    final Join<Predicate,Pnr> join =root.join("pnr",JoinType.LEFT);
                    lstPredicates.add(cb.equal(join.get("issueOfficeCode"), issueOfficeCode));
                }
                if (StringUtils.isNotBlank(type)) {
                    lstPredicates.add(cb.equal(root.get("type"), type));
                }
                if (lstPredicates.size() > 0) {
                    Predicate[] predicates = new Predicate[lstPredicates.size()];
                    query.where(cb.and(lstPredicates.toArray(predicates)));
                }
                query.orderBy(cb.desc(root.get("createTime")));
                return null;
        };
        return specification;
    }

}
